package net.b521.petshop.web.seller;

import net.b521.petshop.common.Const;
import net.b521.petshop.common.ServerResponse;
import net.b521.petshop.dao.SellerMapper;
import net.b521.petshop.dao.model.Classification;
import net.b521.petshop.dao.model.Product;
import net.b521.petshop.dao.model.Seller;
import net.b521.petshop.dao.model.User;
import net.b521.petshop.entity.pojo.ResultBean;
import net.b521.petshop.service.ClassificationService;
import net.b521.petshop.service.ProductService;
import net.b521.petshop.service.StoreService;
import net.b521.petshop.service.UserService;
import net.b521.petshop.service.exception.LoginException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/seller")
public class SellerController {


    @Autowired
    private UserService userService;

    @Autowired
    private StoreService storeService;

    @Autowired
    private ProductService productService;

    @Autowired
    private ClassificationService classificationService;

    @Autowired
    private SellerMapper sellerMapper;


    /**
     * 访问首页
     *
     * @return
     */
    @RequestMapping("/toIndex.html")
    public String toIndex(HttpServletRequest request, HttpServletResponse response) {
        Object login_user = request.getSession().getAttribute("user");
        if (login_user == null) {
            return "redirect:toLogin.html";
        }
        return "seller/index";
    }

    @RequestMapping("")
    public String toAdminLogin() {
        return "redirect:seller/toLogin.html";
    }

    /**
     * 访问登录页面
     *
     * @return
     */
    @RequestMapping("/toLogin.html")
    public String toLogin() {
        return "seller/login";
    }

    /**
     * 访问登录页面
     *
     * @return
     */
    @RequestMapping("/to.html")
    public String to() {
        return "admin/login";
    }

    /**
     * 访问注册开店页面
     *
     * @return
     */
    @RequestMapping("/toRegister.html")
    public String toRegister() {
        return "seller/register";
    }

    @RequestMapping("/toList.html")
    public String toList() {
        return "seller/list";
    }

    @RequestMapping("/toAdd.html")
    public String toAdd() {
        return "seller/add";
    }

    @RequestMapping("/toEdit.html")
    public String toEdit(int id, Map<String, Object> map) {
        Product product = productService.findById(id);
        Classification classification = classificationService.findById(product.getCsid());
        product.setCategorySec(classification);
        map.put("product", product);
        // map.put("message", "添加成功!");
        return "seller/edit";
    }



    @RequestMapping("/login.do")
    public void login(String username,
                      String password,
                      HttpServletResponse response,
                      HttpSession session) throws IOException {
        User user = userService.checkLogin(username, password);
        if (user == null) {
            throw new LoginException("账号不存在~");
        }
        if (user.getRole() != 1) {
            throw new LoginException("对不起,您还不是店铺商家!");
        }
        if (user != null) {
            //登录成功 重定向到首页
            // request.getSession().setAttribute("user", user);
            user.setPassword("");
            Seller seller = userService.saveSeller(user);
            session.setAttribute("user", user);
            session.setAttribute("seller", seller);

            response.sendRedirect("/mall/seller/toIndex.html");
        } else {
            throw new LoginException("登录失败!店铺名或者密码错误");
        }

    }

    @RequestMapping("register.do")
    public String register(String username,
                              String password,
                              String storeName,
                              String name,
                              String phone,
                              String detail,
                              String email,
                              String addr,
                              HttpServletResponse response, HttpSession session){
        User currentUser = (User)session.getAttribute(Const.CURRENT_USER);
        if (null == currentUser) {
            throw new LoginException("请先回首页登录用户");
        }
        if (currentUser.getRole() == 1) {
            throw new LoginException("您已经是店家了!,请直接登录~");
        }
        currentUser.setRole(1);
        currentUser.setPassword(password);
        userService.update(currentUser);
        Seller seller = new Seller();
        seller.setUserId(currentUser.getId());
        seller.setStoreName(storeName);
        seller.setDetail(detail);
        seller.setStatus("1");
        int rowCount = sellerMapper.insertSelective(seller);
        if (rowCount > 0) {
            session.setAttribute("user", currentUser);
            session.setAttribute("seller", seller);
            // return "redirect:mall/seller/toLogin.html";
            return "redirect:toLogin.html";
        } else {
            throw new LoginException("开店失败");
        }
    }

    @RequestMapping("add")
    @ResponseBody
    public ServerResponse add(String username,
                              String password,
                              String storeName,
                              String name,
                              String phone,
                              String detail,
                              String email,
                              String addr,
                              HttpServletResponse response, HttpSession session){
        User currentUser = (User)session.getAttribute(Const.CURRENT_USER);
        if (null == currentUser) {
            return ServerResponse.createByNeedLogin();
        }
        Seller seller = new Seller();
        seller.setStoreName(storeName);
        seller.setDetail(detail);
        seller.setStatus("1");
        int rowCount = sellerMapper.insertSelective(seller);
        if (rowCount > 0) {
            return ServerResponse.createBySuccessMessage("checkUsername.do开店成功,好运连连，祝你生意兴隆");
        }
        return ServerResponse.createByErrorMessage("开店失败");
    }

    /**
     * 验证用户名是否唯一
     * @param username
     * @return
     */
    @ResponseBody
    @RequestMapping("/checkUsername.do")
    public ResultBean<Boolean> checkUsername(String username){
        List<User> users = userService.findByUsername(username);
        if (users==null||users.isEmpty()){
            return new ResultBean<>(true);
        }
        return new ResultBean<>(false);
    }



    @RequestMapping("store_detail")
    @ResponseBody
    public ServerResponse getStoreDetail(Integer storeId, HttpSession session){
        User currentUser = (User)session.getAttribute(Const.CURRENT_USER);
        if (null == currentUser) {
            return ServerResponse.createByNeedLogin();
        }
        if (null == storeId) {
            return ServerResponse.createByIllegalArgument();
        }
        return storeService.getStoreDetail(storeId, currentUser.getId());
    }

    @RequestMapping("list_store")
    @ResponseBody
    public ServerResponse listStore( HttpSession session){
        User currentUser = (User)session.getAttribute(Const.CURRENT_USER);
        if (null == currentUser) {
            return ServerResponse.createByNeedLogin();
        }
        return storeService.listStore();
    }

    @RequestMapping("set_store_name")
    @ResponseBody
    public ServerResponse setStoreName(Integer storeId, String storeName, HttpSession session) {
        User currentUser = (User)session.getAttribute(Const.CURRENT_USER);
        if (null == currentUser) {
            return ServerResponse.createByNeedLogin();
        }

        if (null == storeId || StringUtils.isBlank(storeName)) {
            return ServerResponse.createByIllegalArgument();
        }
        return storeService.setStoreName(storeId, storeName);
    }

    @RequestMapping("close_store")
    @ResponseBody
    public ServerResponse closeStore(Integer storeId, HttpSession session) {
        User currentUser = (User)session.getAttribute(Const.CURRENT_USER);
        if (null == currentUser) {
            return ServerResponse.createByNeedLogin();
        }
        if (null == storeId) {
            return ServerResponse.createByIllegalArgument();
        }
        return storeService.closeStore(storeId, currentUser.getId());
    }




}
